import 'dart:convert';
import 'package:aitao_flutter/model/im/video_chat_model.dart';
import 'package:aitao_flutter/request/api.dart';
import 'package:aitao_flutter/request/requestManager.dart';
import 'package:aitao_flutter/routes/routes.dart';
import 'package:aitao_flutter/utils/log_utils.dart';
import 'package:aitao_flutter/utils/sp_utils.dart';
import 'package:aitao_flutter/utils/time_utils.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:just_audio/just_audio.dart';
import 'package:nim_core/nim_core.dart';
import 'package:vibration/vibration.dart';

class IMNotificationManager {
  final player = AudioPlayer();
  var notiList = <Map>[];
  // 私有构造函数，防止外部实例化
  IMNotificationManager._privateConstructor();

  // 单例实例
  static final IMNotificationManager _instance =
      IMNotificationManager._privateConstructor();

  // 获取单例实例的方法
  factory IMNotificationManager() {
    return _instance;
  }

  // 添加你的单例类的其他方法和属性
  void init() {
    debugPrint('添加你的单例类的其他方法和属性');
    // 视频消息使用系统通知
    NimCore.instance.systemMessageService.onCustomNotification.listen((event) {
      // debugPrint('接收到系统自定义通知2:${event.content}');
      if (event.content != null) {
        try {
          debugPrint('接收到系统自定义通知:${event.content}');
          Map data = json.decode(event.content!);
          notiList.add(data);
          // ios判断是否在前台运行
          if (SpUtil.getAppLifeState()) {
            debugPrint('App在前台运行');
            handelDictData();
          }
        } catch (e) {
          debugPrint('接收到系统自定义通知:${event.content}');
          debugPrint('字符串不是有效的JSON格式');
        }
      }
      //   飘屏字段content 12
    });

    // NimCore.instance.messageService.onMessageStatus.listen((event) {
    //   debugPrint('消息状态变化');
    // });

    // 普通消息使用消息通知
    NimCore.instance.messageService.onMessage.listen((messages) {
      debugPrint('监听到消息');
      if (SpUtil.getIsVideo()) {
        // 视频中不播放提示音
        return;
      }
      NIMMessage message = messages.first;
      debugPrint('消息发送方昵称: ${message.fromNickname} 消息文本  ${message.content}');
      // playMessageAudioTip(message);
      // Future.delayed(const Duration(milliseconds: 500), () {
      //   isPlaying = false;
      //   player.stop();
      // });
    });
  }

  playMessageAudioTip(NIMMessage message) {
    bool needPlay = true;
    bool needShake = true;
    //TODO: 判断当前页面是否需要播放消息提示音
    if (SpUtil.getSystemVoiceStatus() == false) {
      needPlay = false;
    }
    if (SpUtil.getSystemVibrationStatus() == false) {
      needShake = false;
    }
    if (needShake) {
      // 收到消息手机振动
      Vibration.vibrate();
    }
    if (needPlay) {
      player.stop();
      player.setAsset('assets/audio/message.mp3');
      player.play();
    }
  }

  void handelDictData() async {
    for (Map item in notiList) {
      int notiId = int.parse(item['id'].toString());
      if (notiId == 11) {
        debugPrint('视频来电了:$notiId');
        String callTime = item['data']['callTime'].toString();
        if (TimeUtils.getNowTimestamp() - int.parse(callTime) > 180) {
          debugPrint('时间超');
          continue;
        }
        if (SpUtil.getIsVideo() && notiList.isEmpty) {
          debugPrint('视频中或者没有消息了');
          continue;
        } else {
          // 视频处理
          String roomid = item['data']['roomid'].toString();
          if (roomid.isEmpty || roomid == '' || roomid == '0') return;
          var result = await RequestManager()
              .post(API.checkVideo, params: {'room_id': roomid});
          debugPrint('根据房间ID:$roomid获取房间信息');
          WJLogUtils.wjLog(result);
          if (result != null && result['code'] == 0) {
            debugPrint('跳转到视频页面');
            // if (SpUtil.getIsVideo() == false) {
            //   SpUtil.saveIsVideo(true);
            //   // 这里跳转到视频页面
            // }
            VideoChatModel model = VideoChatModel.fromJson(result['data']);
            Get.toNamed(Routes.videoChatPage,
                parameters: {'model': json.encode(model)});
          }
        }
      } else if (notiId >= 12 && notiId <= 14) {
        debugPrint('这里做飘屏的处理:$notiId');
      } else if (notiId == 15) {
        debugPrint('这里做推送:$notiId');
      }
    }
    notiList.clear();
  }
}
